package com.osfw.framework.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.SaTokenException;
import com.baomidou.mybatisplus.extension.api.R;
import com.osfw.framework.core.domain.RestfulResult;
import com.osfw.framework.utils.ServletUtils;
import com.osfw.framework.utils.StringUtils;
import com.osfw.framework.utils.html.EscapeUtil;
import com.osfw.framework.utils.http.RequestUtil;
import com.osfw.framework.utils.security.SaTokenUtils;
import com.osfw.framework.utils.text.Convert;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    /**
     * 权限校验异常（ajax请求返回json，redirect请求跳转页面）
     */
    /*@SneakyThrows
    @ExceptionHandler(NotLoginException.class)
    public Object handleNotLoginException(SaTokenException e, HttpServletRequest request) {
        return null;
    }*/

    /**
     * 权限校验异常（ajax请求返回json，redirect请求跳转页面）
     */
    @SneakyThrows
    @ExceptionHandler(SaTokenException.class)
    public Object handleSaTokenException(SaTokenException e, HttpServletRequest request) {
        Map<String, String> saTokenErrorMsg = SaTokenUtils.getViewAndMsg(e);

        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',SaToken校验失败'{}'", requestURI, e.getMessage());
        if (ServletUtils.isAjaxRequest(request) ||  (!request.getMethod().equalsIgnoreCase("GET") &&  !request.getMethod().equalsIgnoreCase("DELETE")) || saTokenErrorMsg.get("redirectView") == null) {
            if(RestfulResult.Type.UNSAFE.value() == Integer.valueOf(saTokenErrorMsg.get("code")).intValue()){
                return RestfulResult.unsafe(saTokenErrorMsg.get("errorMessage"));
            }else {
                return RestfulResult.error(saTokenErrorMsg.get("errorMessage"));
            }
        } else {
            request.getSession().setAttribute("errorMessage", saTokenErrorMsg.get("errorMessage"));
            return new RedirectView(RequestUtil.getBasePath(request) + saTokenErrorMsg.get("redirectView"));
        }
    }

    /**
     * 用户异常
     */
    @ExceptionHandler(UserException.class)
    public RestfulResult handleUserException(UserException e) {
        log.error("用户验证异常.", e);
        return RestfulResult.error(e.getMessage());
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public Object handleServiceException(ServiceException e, HttpServletRequest request) {
        log.error(e.getMessage(), e);
        if (ServletUtils.isAjaxRequest(request)) {
            return RestfulResult.error(e.getMessage());
        } else {
            return new ModelAndView("osfw/common/error/service", "errorMessage", e.getMessage());
        }
    }

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public RestfulResult handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod(), e);
        return RestfulResult.error(StringUtils.format("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod()));
    }

    /**
     * 请求路径中缺少必需的路径变量
     */
    @ExceptionHandler(MissingPathVariableException.class)
    public RestfulResult handleMissingPathVariableException(MissingPathVariableException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求路径中缺少必需的路径变量'{}',发生系统异常.", requestURI, e);
        return RestfulResult.error(String.format("请求路径中缺少必需的路径变量[%s]", e.getVariableName()));
    }

    /**
     * 请求参数类型不匹配
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public RestfulResult handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        String value = Convert.toStr(e.getValue());
        if (StringUtils.isNotEmpty(value)) {
            value = EscapeUtil.clean(value);
        }
        log.error("请求参数类型不匹配'{}',发生系统异常.", requestURI, e);
        return RestfulResult.error(String.format("请求参数类型不匹配，参数[%s]要求类型为：'%s'，但输入值为：'%s'", e.getName(), e.getRequiredType().getName(), value));
    }

    /**
     * 拦截自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public RestfulResult handleBindException(BindException e) {
        log.error(e.getMessage(), e);
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return RestfulResult.error(message);
    }

    /**
     * 拦截未知的Servlet异常
     */
    @ExceptionHandler(ServletException.class)
    public RestfulResult handleServletException(ServletException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生未知异常.", requestURI, e);
        return RestfulResult.error("服务器发生未知异常，请联系管理员");
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public RestfulResult handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生未知异常.", requestURI, e);
        return RestfulResult.error("服务器发生未知异常，请联系管理员");
    }

    /**
     * 拦截未知的系统异常
     */
    @ExceptionHandler(Exception.class)
    public RestfulResult handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生系统异常.", requestURI, e);
        return RestfulResult.error("服务器发生未知异常，请联系管理员");
    }

}
